﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Entity;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using Common.Background.Service;
using Web.Attributes;
using Common.Background.Entity;
using VCommons;
namespace Common.Background.Web.Controllers
{
    [HandleError]
    public class AccountController : BackgroundBaseController
    {

        IWebManageMenusSerivces _webmanagemenusserivces = null;
        public AccountController()
        {

            this._webmanagemenusserivces = new WebManageMenusServices();
        }


        #region 登陆

        /// <summary>
        /// 初始化登陆页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult LogOn()
        {
            WebManageUsers webuser = new WebManageUsers();
            return View(webuser);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOn(WebManageUsers webuser)
        {
            string _code = VCommons.Http.CookieHelper.Read("RandomCode").ToLower();
            if (Request.Form["RandomCode"].ToLower() != _code)
            {
                ViewData["Result"] = "验证码错误！";
                return View();
            }

                VMessage msg = _webmanagemenusserivces.ManageuaerLogin(webuser);
            if (msg.IsComplete)
            {

                WebManageUsers user_Info = (WebManageUsers)msg.Entity;
                SessionAction.WriteSession("Background_Current_UserID", user_Info.ManageUserID);
                SessionAction.WriteSession("Background_Current_UserName", user_Info.LoginName);
                SessionAction.WriteSession("Background_Current_Dept", user_Info.DepartmentID);
                SessionAction.WriteSession("Background_Current_DeptName", user_Info.WebDepartments_Extend.DepartmentName);
                UserOperatorRole userOperatorRole = UserOperatorRole.NoneAny;
                user_Info.WebManageUser_WebManageRoles_Extend.ToList().ForEach(i =>
                {
                    userOperatorRole |= (UserOperatorRole)i.WebManageRoles_Extend.OperatorAuthority;
                });
                SessionAction.WriteSession("UserOperatorRole", (int)userOperatorRole);

                LogOnEvent.OnLogOnAfter();
              
                if (Request.QueryString["returnUrl"] != null)
                    return Redirect(Request.QueryString["returnUrl"]);
                else
                    return RedirectToAction("MenuManage");//登陆成功后跳转的页面
            }
            else
            {
                ViewData["Result"] = msg[0];
                return View(new WebManageUsers());
            }
        }
        #endregion

        #region 登出
        /// <summary>
        /// 退出系统
        /// </summary>
        /// <returns></returns>
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult ExitSysTem()
        {
            ExitEvent.OnExitAfter();
            Response.Buffer = true;  //登录后禁止回退
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "No-Cache");
            Session["Background_Current_UserID"] = -new Random().Next(2, 99999999);
            return Json(new { result = true });
        }
        #endregion

        #region 修改密码
        /// <summary>
        /// 初始化修改密码的页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult ModifyPassword()
        {
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="webuser"></param>
        /// <returns></returns>
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult ModifyPassword(WebManageUsers webuser)
        {
            webuser.ManageUserID = Background_Current_UserID;
            webuser.Password = VCommons.Encryptor.Utility.EncryptString(Request.Form["oldpassword"].ToString(), VCommons.Encryptor.Utility.EncryptorType.MD5);
            webuser.LoginName = Current_UserName;
            string newpassword = VCommons.Encryptor.Utility.EncryptString(Request.Form["newpassword"].ToString(), VCommons.Encryptor.Utility.EncryptorType.MD5);
            bool flag = _webmanagemenusserivces.UpdatePassword(webuser, newpassword);
            ViewData["UserName"] = Current_UserName;
            if (flag == true)
            {
                ViewData["Modify_Result"] = "修改成功";
            }
            else
            {
                ViewData["Modify_Result"] = "原始密码输入错误";
            }
            return View();
        }
        #endregion

        #region 菜单管理

        /// <summary>
        /// 初始化后台框架页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult MenuManage(string status)
        {
            ExitEvent.ExitAfter += new Action(ExitEvent_ExitAfter);
            return View();
        }

        void ExitEvent_ExitAfter()
        {
            SessionAction.WriteSession("Background_Current_UserName", " ");
        }

        /// <summary>
        /// 初始化状态栏
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult StatusBar()
        {
            ViewData["UserName"] = base.Background_Current_UserName;
            List<WebManageMenus> webmanagemenus = _webmanagemenusserivces.GetManageMenus(Background_Current_UserID, 1);
            StringBuilder html = new StringBuilder();
            html.Append("<ul>");
            foreach (var item in webmanagemenus)
            {
                this.GetMenu(html, item);
            }
            html.Append("</ul>");

            ViewData["Menu"] = html.ToString();
            return View();
        }

        private void GetMenu(StringBuilder html, WebManageMenus webmanagemenu)
        {
            html.Append("<li>");
            html.Append("<a  href='/Account/MenuTree?id=" + webmanagemenu.MenuID + "' target='LeftFrm'>");
            html.Append(webmanagemenu.MenuName);
            html.Append("</a>");
            html.Append("</li>");
        }
        /// <summary>
        /// 初始化左侧树形菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult MenuTree()
        {
            List<WebManageMenus> webmenus;
            if (Request.QueryString["id"] != null)
            {
                webmenus = _webmanagemenusserivces.GetManageMenus(Background_Current_UserID, int.Parse(Request.QueryString["id"].ToString()));
            }
            else
            {
                webmenus = _webmanagemenusserivces.GetManageMenus(Background_Current_UserID, 1);
            }
            if (webmenus.Count() > 0)
            {
                StringBuilder html = new StringBuilder();
                webmenus.ForEach(i =>
               {
                   List<WebManageMenus> webmanagemenus = _webmanagemenusserivces.GetMenusChildNode(Background_Current_UserID, i.MenuID);
                   html.Append("<ul>");
                   html.Append("<li class='explode' name='menu'>");
                   html.Append(i.MenuName);
                   if (webmanagemenus.Count() > 0)
                   {
                       ViewData["InitLink"] = "/Account/operatMain";
                   }
                   foreach (var item in webmanagemenus)
                   {
                       html.Append("<ul>");
                       this.GetTreeMenu(html, item);
                       html.Append("</ul>");
                   }
                   html.Append("</li>");
                   html.Append("</ul>");

               });
                ViewData["MenuTree"] = html.ToString();

            }
            return View();
        }

        /// <summary>
        /// 得到树形结构
        /// </summary>
        /// <param name="html"></param>
        /// <param name="webmanagemenu"></param>
        private void GetTreeMenu(StringBuilder html, WebManageMenus webmanagemenu)
        {
            html.Append("<li class='menu-item'>");
            html.Append("<a read='" + webmanagemenu.Status + "' href='" + webmanagemenu.LinkUrl + "' target=\"MainFrm\">");
            html.Append(webmanagemenu.MenuName);
            html.Append("</a>");
            List<WebManageMenus> childmanagemenus = _webmanagemenusserivces.GetMenusChildNode(Background_Current_UserID, webmanagemenu.MenuID);
            if (childmanagemenus != null && childmanagemenus.Count > 0)
            {
                html.Append("<ul>");
                foreach (var item in childmanagemenus)
                {
                    this.GetTreeMenu(html, item);
                }
                html.Append("</ul>");
            }
            html.Append("</li>");
        }
        /// <summary>
        /// 初始化右侧操作页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [UserAuthentication(AuthenticationType.BackgroundLogin)]
        public ActionResult OperatMain()
        {
            return View();
        }



        #endregion

        #region   生成验证码
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public FileContentResult RandomPic()
        {
            int charNum = 4;
            string VNum = MakeVerifyCode(charNum);
            VCommons.Http.CookieHelper.Write("RandomCode", VNum);
            return File(CreatePicCode(VNum), "image/JPEG");
        }
        public static string MakeVerifyCode(int Numberlength)
        {
            string strTemp = "";
            string randomchars = "abcdefghijklmnpqrstuvwxyz123456789";
            randomchars = randomchars.ToUpper();
            int iRandNum;
            Random rnd = new Random();
            for (int i = 0; i < Numberlength; i++)
            {
                iRandNum = rnd.Next(randomchars.Length);
                strTemp += randomchars[iRandNum];
            }
            return strTemp;
        }
        private byte[] CreatePicCode(string VNum)
        {
            int gWidth = (int)(VNum.Length * 17);// Gwidth为图片宽度,根据字符长度自动更改图片宽度
            int gHeight = 20;
            System.Drawing.Bitmap Img = new System.Drawing.Bitmap(gWidth, gHeight);

            Graphics g;
            MemoryStream ms = new MemoryStream();

            string tmpstr = "";
            for (int mm = 0; mm < VNum.Length; mm++)
            {
                tmpstr += VNum[mm] + " ";
            }
            VNum = tmpstr;


            g = Graphics.FromImage(Img);

            SolidBrush drawBrushNew = new SolidBrush(Color.White);
            g.FillRectangle(drawBrushNew, 0, 0, Img.Width, Img.Height);

            // Create font and brush.	

            FontStyle style = FontStyle.Bold;
            //style |= FontStyle.Bold;
            Font drawFont = new Font("Arial", 12, style);

            SolidBrush drawBrush = new SolidBrush(Color.Red);


            Color clr = Color.Red;
            Pen p = new Pen(clr, StrDeal.LoginRandNum(1, 4));
            int x1 = StrDeal.LoginRandNum(1, gWidth);
            int y1 = StrDeal.LoginRandNum(1, gHeight);
            int x2 = x1 + StrDeal.LoginRandNum(15, gWidth - 15);
            int y2 = y1 + StrDeal.LoginRandNum(0, gHeight);
            PointF drawPoint1 = new PointF(x1, y1);
            PointF drawPoint2 = new PointF(x2, y2);

            for (int i = 0; i < Convert.ToInt32(StrDeal.LoginRandNum(300, 415)); i++)
            {
                // 生成一个随机宽度
                clr = Color.FromArgb(StrDeal.LoginRandNum(100, 255), StrDeal.LoginRandNum(51, 255), StrDeal.LoginRandNum(11, 255));
                p.Color = clr;
                p.Width = StrDeal.LoginRandNum(1, 4);

                x1 = StrDeal.LoginRandNum(1, gWidth);
                y1 = StrDeal.LoginRandNum(1, gHeight);
                x2 = x1 + StrDeal.LoginRandNum(15, gWidth - 15);
                y2 = y1 + StrDeal.LoginRandNum(0, gHeight);
                drawPoint1.X = x1;
                drawPoint1.Y = y1;
                drawPoint2.X = x2;
                drawPoint2.Y = y2;
                g.DrawLine(p, drawPoint1, drawPoint2);

            }
            p.Dispose();
            PointF drawPoint = new PointF(3, 3);
            g.DrawString(VNum, drawFont, drawBrush, drawPoint); //在矩形内绘制字串（字串，字体，画笔颜色，左上x.左上y）

            Img.Save(ms, ImageFormat.Jpeg);

            return ms.ToArray();


        }
        public class StrDeal
        {
            public StrDeal()
            {
                //
                // TODO: 在此处添加构造函数逻辑
                //
            }

            /// <summary>
            ///     将指定的字符串中危险字符替换，返回已处理完的字符串。
            ///     <remarks>主要处理SQL语句中危险字符</remarks> 
            ///     <param name="strContent">要处理的字符串。</param>
            /// </summary>
            public static String FilterSql(object strContent)
            {
                if (strContent == null)
                {
                    return "";
                }
                if (strContent.ToString() == "")
                {
                    return "";
                }
                else
                {
                    string rStr = "";
                    rStr = ((string)strContent).Trim().Replace("'", "‘");


                    // 处理xml的保留字符
                    //				rStr = rStr.Replace("<","〈");
                    //				rStr = rStr.Replace(">","〉");
                    //
                    //				rStr = rStr.Replace("\"","〝");
                    //				rStr = rStr.Replace("&","﹠");

                    return rStr;
                }
            }


            public static string[] StringSplit(string strSource, string strSplit)
            {
                string[] textArray1 = new string[1];
                int num1 = strSource.IndexOf(strSplit, 0);
                if (num1 < 0)
                {
                    textArray1[0] = strSource;
                    return textArray1;
                }
                textArray1[0] = strSource.Substring(0, num1);
                return StrDeal.StringSplit(strSource.Substring(num1 + strSplit.Length), strSplit, textArray1);
            }

            public static string[] StringSplit(string strSource, string strSplit, string[] attachArray)
            {
                string[] textArray1 = new string[attachArray.Length + 1];
                attachArray.CopyTo(textArray1, 0);
                int num1 = strSource.IndexOf(strSplit, 0);
                if (num1 < 0)
                {
                    textArray1[attachArray.Length] = strSource;
                    return textArray1;
                }
                textArray1[attachArray.Length] = strSource.Substring(0, num1);
                return StrDeal.StringSplit(strSource.Substring(num1 + strSplit.Length), strSplit, textArray1);


            }


            /// <summary>
            ///     判断获得的字符是否能转换为数字
            ///     <remarks></remarks> 
            ///     <param name="strContent">要处理的字符串。</param>
            /// </summary>
            public static bool IsNum(string strContent)
            {
                try
                {
                    Decimal.Parse(strContent);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            /// <summary>
            ///     判断获得的字符是否能转换为数字
            ///     <remarks></remarks> 
            ///     <param name="strContent">要处理的字符串。</param>
            /// </summary>
            public static bool IsInt(string strContent)
            {
                try
                {
                    int.Parse(strContent);
                    return true;
                }
                catch
                {
                    return false;
                }
            }

            /// <summary>
            ///     返回一个登录随机数
            ///     <remarks></remarks> 
            ///     <param name="minValue">随机数下限。</param>
            ///     <param name="maxValue">随机数上限。</param>
            /// </summary>
            public static int LoginRandNum(int minValue, int maxValue)
            {
                try
                {

                    Random ro = new Random();
                    return ro.Next(minValue, maxValue);

                }
                catch
                {
                    return 8888;
                }
            }

            //格式化一个单号
            //by wmj
            public string formatBillId(string formatStr, int MaxlengthOfNum, string billValue)
            {
                if (!(formatStr == "yyyyMMdd") | (formatStr == "yyyyMM") | (formatStr == "yyyy"))
                {
                    throw new Exception("无效的参数formatStr，formatBillId函数调用失败！");
                }

                return DateTime.Now.ToString(formatStr).Trim() + billValue.PadLeft(MaxlengthOfNum, '0').Trim();
            }
        }
        #endregion

    }
}
